#!/bin/sh
set -eu

top_srcdir=$(realpath -m "$0"/../../..)
image=ghcr.io/cockpit-project/unit-tests:latest
no_npm=''
scenario=''
flags=''
cmd=''
results_vol=''

while test $# -gt 0; do
  case "$1" in
    --docker) docker="docker";;
    --podman) docker="podman";;
    NO_NPM=1) no_npm='--env=NO_NPM=1';; # noop
    CC=*) ccarg="--env=$1";;
    shell) flags=-it; cmd=/bin/bash;;
    :*) image=ghcr.io/cockpit-project/unit-tests"$1";;
    distcheck|check-memory) scenario="--env=TEST_SCENARIO=$1";;
    dist)
        scenario="--env=TEST_SCENARIO=$1"
        results_vol="--volume=${top_srcdir}/tmp/dist:/results:Z"
        mkdir -m 777 -p "${top_srcdir}/tmp/dist"
        ;;

    *) echo "Unknown option '$1'"; exit 1;;
  esac
  shift
done

if test -z "$scenario" -a -z "$cmd"; then
  echo 'Must specify a scenario or `shell`'
  exit 1
fi

if test -z "${docker:=$(which podman || which docker || true)}"; then
  echo 'Neither podman nor docker are installed'
  exit 1
fi

set -ex
exec ${docker} run --shm-size=512M --volume "${top_srcdir}":/source:ro \
       ${results_vol:+"$results_vol"} \
       ${ccarg:+"$ccarg"} $scenario $no_npm $flags -- "$image" $cmd
